import type { Users } from "@/api/model/userSearchTypes";
import { reqSearchUsers } from "@/api/userSearch";
import { RootState } from "@/app/store";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";


// 状态类型
interface UserSearchState {
  firstView: boolean;
	loading: boolean;
	errorMsg: string;
	users: Users
}

const initialState: UserSearchState = {
  firstView: true,
	loading: false,
	errorMsg: '',
	users: []
}


// 创建一个搜索的异步action
export const searchAsync = createAsyncThunk(
  'userSearch/searchAsync',
  (searchName: string) => reqSearchUsers(searchName)   // 成功的value是response / 失败的reason是error
)

// axios.get('xxxx').then(response => {}, (error) => {})

// 创建slice对象
const userSearchSlice = createSlice({
  name: 'userSearch', // 标识名称
  initialState, // 初始状态
  // 配置用于生成同步action creator的reducer
  reducers: {},
  // 为外面创建的异步action creator定义对应的reducer
  extraReducers: (builder) => {
    builder
      // 异步请求前处理
      .addCase(searchAsync.pending, (state) => { // type: userSearch/searchAsync/pending
        state.firstView = false
        state.loading = true
        state.errorMsg = ''
        state.users = []
      })
      // 异步请求成功后处理
      .addCase(searchAsync.fulfilled, (state, action) => { // type: userSearch/searchAsync/fulfilled
        state.loading = false
        state.users = action.payload.items
      })
      // 异步请求失败后处理
      .addCase(searchAsync.rejected, (state, action) => { // type: userSearch/searchAsync/rejected
        state.loading = false
        state.errorMsg = action.error.message || '未知错误'
      })
  }, 
})

// 暴露reducer
export const userSearchReducer = userSearchSlice.reducer

// 用于读取当前状态数据select函数
export const selectUserSearch = (state: RootState) => state.userSearch